package cn.btks.backstagemanage.division.service.impl;

import cn.btks.backstagemanage.division.dto.DivisionDto;
import cn.btks.backstagemanage.division.pojo.City;
import cn.btks.backstagemanage.division.pojo.County;
import cn.btks.backstagemanage.division.repository.CityRepository;
import cn.btks.backstagemanage.division.repository.CountyRepository;
import cn.btks.backstagemanage.division.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/1/25 11:03
 */
@Service
public class CityServiceImpl implements CityService {

    @Autowired
    CityRepository cityRepository;

    @Autowired
    CountyRepository countyRepository;

    @Override
    public City findById(Long id) {
        Optional<City> optional = cityRepository.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public City findByCountyName(String countyName) {
        County county = countyRepository.findByName(countyName);
        Long cityId = Long.valueOf(0);
        if(county.getEscrowId() != null){
            cityId = county.getEscrowId();
        }else {
            cityId = county.getCityId();
        }
        Optional<City> optional = cityRepository.findById(cityId);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<City> findAll() {
        return cityRepository.findAll();
    }

    @Override
    public List<City> findAllByIsShow(Integer isShow) {
        return cityRepository.findAllByIsShow(isShow);
    }

    @Override
    public City findByCityName(String cityName) {
        return cityRepository.findByName(cityName);
    }

    @Override
    public List<DivisionDto> findAllCityAndCounty() {
        List<DivisionDto> divisionDtos = new ArrayList<>();
        List<City> cityList = cityRepository.findAll();
        if(cityList != null && cityList.size() > 0){
            for (City city : cityList){
                DivisionDto divisionDto = new DivisionDto();
                divisionDto.setCity(city);
                List<County> countyList = countyRepository.findAllByCityId(city.getId());
                divisionDto.setCountyList(countyList);
                divisionDtos.add(divisionDto);
            }
        }
        return divisionDtos;
    }
}
